package com.haois.mp.wechat.config;

import cn.zhouyafeng.itchat4j.Wechat;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.service.ILoginService;
import cn.zhouyafeng.itchat4j.service.impl.LoginServiceImpl;
import com.haois.mp.database.module.person.service.SimpleDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.CountDownLatch;


/**
 * description
 *
 * @author RuiHaoZ on hgits.cn
 * @date 2019/2/28 8:45
 */
//@Component
public class PersonConfig {

    @Value("${defined.person.material-path}")
    private String itChatPath;

    @Autowired
    @Qualifier("taskExecutor")
    private ThreadPoolTaskExecutor taskExecutor;

    private ILoginService loginService = new LoginServiceImpl();

    @PostConstruct
    public void weChatLogin() {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        taskExecutor.submit(() -> {
            try {
                // 保存登陆二维码图片的路径，这里需要在本地新建目录
                // 实现IMsgHandlerFace接口的类
                IMsgHandlerFace msgHandler = new SimpleDemo(itChatPath);
                // 【注入】
                Wechat wechat = new Wechat(msgHandler, itChatPath);
                // 启动服务，会在qrPath下生成一张二维码图片，扫描即可登陆，注意，二维码图片如果超过一定时间未扫描会过期，
                // 过期时会自动更新，所以你可能需要重新打开图片
                wechat.start();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            return null;
        });
        try {
//            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostConstruct
    public void refuse() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        taskExecutor.submit(() -> {
            try {
                ((Runnable) () -> {
                    {
                        while (true) {
                            try {
                                Thread.sleep(6000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
//                            System.out.println("zxx...........................");
                            loginService.WebWxBatchGetContact();
                            loginService.webWxGetContact();
                        }
                    }
                }).run();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            return null;
        });

    }
}
